Repository navigation
Conversation
…nlockForUsage UnlockForUsage released the read lock on the layered profile first and only then iterated lp.layers to read-unlock every layer. As soon as the layered profile lock is released, a concurrent LayeredProfile.Update (called by the firewall for another connection of the same process when a layer is outdated, eg. after the user changed the app settings) can take the write lock and replace lp.layers[i] with the new profile version. UnlockForUsage then reads lp.layers unsynchronized (data race) and calls RUnlock on the new layer, which it never locked, instead of the old one: - if the new layer is not read-locked by anyone, the runtime aborts the whole process with "fatal error: sync: RUnlock of unlocked RWMutex"; - otherwise it steals another reader's lock, and the old layer stays read-locked forever, so any later Lock() of it blocks indefinitely. Fix: read-unlock the layers while still holding the layered profile read lock, so the set of unlocked layers is the set that LockForUsage locked. Proof: TestLayeredProfileUnlockForUsageDuringUpdate (LockForUsage, newer profile becomes active, concurrent Update, UnlockForUsage). Before, with -race: "WARNING: DATA RACE" write at (*LayeredProfile).Update() (profile-layered.go:288, lp.layers[i] = newLayer) vs. previous read at (*LayeredProfile).UnlockForUsage() (profile-layered.go:171); without -race, -count=20 crashed the test binary with "fatal error: sync: RUnlock of unlocked RWMutex". After: passes -race -count=5 and -count=50. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…nt saves applyUpdate (database.go) read existing.Meta().IsDeleted() without holding the notification lock, while delete() writes Meta().Deleted under the lock: a data race between a user response arriving via the database interface and the expiry cleaner, an action function or any other Delete(). Worse, save() and delete() both updated the global nots map only after releasing the notification lock, and save() did not check the deleted flag. With a response applied concurrently with a deletion, the pending save of the response ran after the delete and re-inserted the already deleted notification into the map. Such a zombie is never removed again (the cleaner's delete() returns early for deleted notifications), it is still returned by notifications.Get() and by the storage Get(), and callers that use Get() != nil as "already shown" (compat, broadcasts) suppress new notifications with that event ID until restart. Fix: check the deleted flag under the lock in applyUpdate, never re-add a deleted notification in save(), and update the map while holding the notification lock (lock order n.lock -> notsLock; notsLock is never held while acquiring a notification lock). Proof: TestApplyUpdateConcurrentDelete (applyUpdate racing delete). Before: "WARNING: DATA RACE" write at record.(*Meta).Delete() (notification.go:451) vs. previous read at (*Meta).IsDeleted() via applyUpdate (database.go:148); and, even without -race, -count=10 reported "1..3 deleted notifications were re-added to the notification storage" (19-31 per run with -race). After: passes -race -count=10, -count=30. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
upgradeMoveFiles sets u.index to the new index as soon as all files are moved. If the following post-upgrade command fails (FailOnError), upgrade() rolls the files back via recoverFromFailedUpgrade, which moves the purged old files, including the old index file, back into the main directory - but u.index kept pointing to the new index. Afterwards the in-memory state contradicts the installed files: GetFile / GetFiles / GetIndex report the new version and SHA256 sums for files that contain the old version, and every later update check compares the new index with itself (same Published date -> ErrSameIndex) and reports "no new update", so the failed upgrade is never retried until a restart reloads the old index from disk. Fix: remember the index before moving files and restore it when the upgrade fails, before the rollback. Proof: TestFailedPostUpgradeCommandRestoresIndex (post-upgrade command "false" with FailOnError). Before: "active index is v1.0.1, but installed files were rolled back to v1.0.0". After: passes with -race -count=3. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ion lock
handleConnection held the lock of the connection while it converted the
connection, wrote it to SQLite (waiting for the database write lock, which
bandwidth updates, the cleaner and history maintenance also take) and
pushed the update. The packet path of that connection (verdict handling,
bandwidth updates, re-evaluation) had to wait for the disk write.
Only take the lock to snapshot the connection: convert it and copy the
metadata and the history flag. The model no longer references the
connection: Allowed pointed at conn.ConnectionEstablished and is now a
copy. Updates of a connection stay in order, as the feed is handled by a
single worker.
TestHandleConnectionSavesUnlocked (store that blocks in Save) failed
before with "connection is locked while it is saved to the store" and
also checks that the saved model does not change with the connection.
Lock hold time per connection update (i7-14700HX, -count=5 medians):
before: all of BenchmarkHandleConnection
history=false 44.7 us, history=true 82.3 us
after: BenchmarkSnapshotConnection 5.4 us
The total cost of handleConnection is unchanged (44.9 us / 83.4 us).
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
… updates Database.Save upserts a connection with ON CONFLICT(id) DO UPDATE SET <every column>. SQLite decides by the columns of the SET list which indexes an UPDATE has to rewrite, not by whether the values change. Every update of a connection (typically two or more per connection, in the live and in the history database) therefore rewrote the primary key index and the started index, although neither value can change: the ID is the conflict target and network.Connection.Started is only set when the connection is created. Only write these two columns on insert. The partial (started, ended) index is still maintained, as ended changes. TestSaveStoresSameRowsAsFullUpdate saves a series of inserts and updates that change every other column, plus bandwidth updates, with the new and with the previous statement and compares all columns of all rows of the live and the history database. BenchmarkHandleConnection (i7-14700HX, -count=5 medians, every connection is saved three times): history=false 44.9 us -> 37.5 us (-16%) history=true 83.4 us -> 64.9 us (-22%) Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
After saving a connection, the manager marshals it to JSON and wraps it in a record to push it to the subscribers of runtime:netquery/conns/. The UI reads connections with SQL queries and does not subscribe to them, so the record was created for every connection update and then dropped by Controller.PushUpdate (about a quarter of the CPU time of handleConnection). Add Controller.HasSubscribers(dbKey) and Registry.HasSubscribers(key), which report whether a subscription matches the key (ignoring permissions and query conditions, so they never report too few), and skip creating the record if there is none. A push only notifies the subscriptions that exist at that moment, so subscribers receive the same updates as before. TestPushConnUpdate checks that a subscriber of the connections still receives the same JSON and that other subscriptions do not count; TestControllerHasSubscribers covers the key matching. BenchmarkHandleConnection without subscribers (i7-14700HX, -count=5 medians): history=false 37.5 us 7409 B 53 allocs -> 30.3 us 5514 B 44 allocs (-19%) history=true 64.9 us 7442 B 54 allocs -> 57.9 us 5547 B 45 allocs (-11%) Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
… the packet The first try of a process lookup used the current socket tables only if the packet was seen after they were last updated, and fetched the tables from the system otherwise. That is the wrong way round for the second case: tables that were fetched after the packet was seen (by the lookup of another packet, while this one was waiting) are as good for this packet as newly fetched ones. Every packet of a burst of new connections that was seen before the first of them refreshed the tables fetched them again, and each fetch waits for the pause between table updates (10 ms) and reads the tables from the system (2.2 ms for 50 TCP4 sockets here, BenchmarkTableFetch), while the packet is held. Always use the current tables for the first try. Nothing changes for packets seen after the last update, and a miss still fetches on the next try. The comment on lookupTries now documents the semantics, including that the first try trusts tables of any age (unchanged). TestLookupFirstTryUsesTablesNewerThanPacket failed before for TCP and UDP with "table was fetched 1 times, although it holds the socket and is newer than the packet", taking 10 ms per lookup. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Since the factory is held in an atomic pointer, SetLocalAddrFactory(nil) stored a pointer to a nil function. It was correctly not called, but it counted as set, so a later call with a real factory was ignored. Before the atomic pointer, setting nil left the factory unset. Restore that. TestSetLocalAddrFactoryOnce failed before with "local address is <nil>, expected the one of the first factory". Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
flushWriteCache writes the whole write cache with one Interface.PutMany batch and then cleared the write cache unconditionally. Since 3bff1b5 a batch that times out on a storage.AbortableBatcher (sqlite, bbolt) is discarded as a whole and its result wraps storage.ErrBatchAborted, so one aborted flush lost every delayed write that was in the write cache. A timeout is possible whenever the flushing goroutine stalls for over a second between two puts (e.g. system suspend, CPU starvation). The write cache is now kept when a put or the finishing put(nil) reports storage.ErrBatchAborted or errPutManyTimeout, and the next regular flush trigger (threshold ticker, eviction trigger, force ticker) retries all of its records. errPutManyTimeout is included because an abortable storage reports a batch that timed out before any record was forwarded only as errPutManyTimeout, and a storage without abort support stores just the records submitted before the timeout; writing a record again is idempotent. Other errors (storage write errors, read-only, permission, shutdown) keep the previous behavior of logging and clearing, as they may be caused by the records themselves and would block every later flush. flushWriteCache holds writeCacheLock throughout, so neither cacheEvictHandler nor updateCache can interleave; kept records are later replaced by newer versions of the same key or written by the evict handler, as for any pending record. On shutdown, DelayedCacheWriter flushes once more, so that an aborted final flush is retried once instead of losing the kept records at exit. The second call is a no-op if the write cache is already empty. Tests: TestFlushWriteCacheKeepsAbortedRecords failed before with "0 records are left in the write cache after the aborted flush, expected 50"; TestDelayedCacheWriterRetriesAbortedFlushOnShutdown failed with "0 records are stored after shutdown, expected 20" (and, with only the flush fix, "20 records are left in the write cache after shutdown"). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The process/list/by-profile and process/group-leader endpoints returned
the live *Process values from their StructFunc. The API layer encodes
the returned value (dsd.MimeDump) after the handler returned, without
holding the process lock, while exported, serialized fields of the
same, already stored processes are written under Process.Lock():
- LastSeen by CleanProcessStorage (SetLastSeen)
- PrimaryProfileID by RefetchProfile/GetProfile (setProfile)
The encoder therefore raced with these writers; a torn read of the
PrimaryProfileID string header can read invalid memory.
Return snapshots instead: snapshotForAPI copies the serialized fields
into a new Process while holding only that process's lock (no other
lock is taken while holding it, and Leader() is resolved before, so
no new lock ordering is introduced). Maps and slices are cloned so the
snapshot is independent of the live process. The copy is built field
by field, so no lock is copied (go vet copylocks stays clean).
record.Base and sync.Mutex have no exported fields, so the encoded
output is unchanged; TestProcessAPIOutputUnchanged compares the JSON,
YAML, CBOR and msgpack output of the live process against the handler
output and fails if a serialized field is left out of the snapshot.
Evidence (TestHandleGetProcessesByProfileRace, go test -race, before
the fix):
WARNING: DATA RACE
Read at 0x00c0002402a8 by goroutine 37:
encoding/json.stringEncoder()
dsd.MimeDump()
process.TestHandleGetProcessesByProfileRace() api_race_test.go
Previous write at 0x00c0002402a8 by goroutine 38:
process.(*Process).setProfile() service/process/profile.go:64
...
Previous write at 0x00c000164d50 by goroutine 38:
process.(*Process).SetLastSeen() service/process/process.go:197
After the fix the test is clean with -race -count=10.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
When ExpandTo failed to start the relay operation on the previous hop, the relay operation was stopped, which abandoned the half-built expansion terminal. But the terminal's workers were only started after the relay operation was started successfully, so the abandon procedure blocked in TerminalBase.Flush on the unbuffered flush channel that only the never-started Sender reads, until the 5 minute flush timeout. During that time the terminal context was not canceled and the stop message unit stayed queued in the flow queue without being finished. Start the expansion terminal's workers before starting the relay operation, so that the abandon procedure completes immediately. Nothing is sent through the terminal before the relay operation is started. Also, establishRoute (spn/crew) did not abandon expansions that it had created but not taken into use when a later step failed (failed or timed-out authentication of this or a later hop, failure to expand to a later hop). These terminals were not referenced anywhere and lingered, together with the relay chain on the hubs, until their idle timeout. Abandon them when building the route fails. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
CapacityTestOp.HandleStop only reported the result and drained the receive queue, but the handler worker did not notice that the operation had stopped. When the remote side stopped the operation or the terminal was abandoned, the handler kept running until the maximum test time or the 30 second operation timeout. Meanwhile it held the global capacityTestRunning lock, so new capacity tests were rejected with "another capacity op is already running", and on reaching the maximum test time it still reported the partial measurement as the lane capacity. Close a stopping channel in HandleStop and let the handler return when it is closed. The sender already ends after its next send, as it checks Stopped(). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The global unit scheduler was replaced with a plain assignment on every start of the terminal module, while messages may be created concurrently (eg. by goroutines still running from the previous run), which is a data race on the scheduler variable and on the newly created scheduler. The metrics also bound the scheduler's getters at their first (and only) registration, so after a restart they kept reporting the stopped scheduler. Hold the scheduler in an atomic.Pointer, publish a new scheduler only after it is set up and read it via getScheduler() everywhere, including in the metric functions. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
delete() removed nots[EventID] without checking that the entry is the notification being deleted. If a notification was replaced by a newer one with the same EventID, deleting the old copy (expiry cleaner or a late Delete()) removed the newer one from the map, making it unreachable while still shown. Only delete the map entry if it is the same object. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
delete() dereferenced n.Meta(), which is nil until the first save, so Delete() on a never-saved notification panicked. For such notifications only release the expiry channel and connected state and return; behaviour for saved notifications is unchanged. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
`defer msg.Finish()` evaluates the receiver when the defer statement runs. In the terminal sender, the crew connect writer, the capacity test handler and the crane loader the variable is nil at that point and only assigned later in the loop, so the deferred call always ran on nil (a no-op). A message that was still held when the worker exited (buffered in the sender, received but not yet finished in the writer/handler/loader) never had its scheduling unit finished, so the scheduler kept counting it. Wrap the calls in closures so the variable is read at exit. Msg.Finish and Unit.Finish are nil-safe and idempotent, so double finishing is harmless. The terminal handler defer is changed the same way for consistency (handleReceive already finishes its msg). Regression test: TestSenderFinishesBufferedUnit. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The DuplexFlowQueue encodes reported receive space as a varint of the full value, while the receiving side parses it with GetNextN16 (max 65535). Queue sizes of up to MaxQueueSize (1,000,000) are allowed, so a report (queue size minus already reported space) could exceed 65535 and the peer failed to parse the flow control message as malformed data. Cap each report at math.MaxUint16 in reportableRecvSpace. Only the capped amount is added to reportedSpace, so the remainder stays accounted and is reported with the next report; a forced report is triggered when capped so it is sent even if no further data flows. The wire format is unchanged. Regression test: TestFlowQueueSpaceReportLimit (fails before with "reported space 200000 does not fit into 16 bits"). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The global rngFeeder was reassigned with a plain assignment on every start of the terminal module while terminals may concurrently read it in handlePaddingMsg, which is a data race (reproduced with -race). Hold the feeder in an atomic.Pointer and read it via getRngFeeder(), like the unit scheduler next to it. Regression test: TestRngFeederRestart (reports a DATA RACE before). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
When an auth operation was stopped without an error, its result is a nil
*terminal.Error, which is neither an error nor ErrExplicitAck and thus
ends up in the "aborted" branch of establishRoute. The branch intended to
replace a missing error with ErrUnknownError, but the condition was
inverted (`tErr != nil`): a nil error stayed nil, so
`tErr.Wrap(...)` (nil-safe, returns nil) was returned through the `error`
return value as a non-nil interface holding a nil pointer. That error has
no message ("<nil>") and panics on Error(). Non-nil results (eg. a
stopping status) were replaced by an unknown error, losing the reason.
Move the check into abortedAuthError and replace only a nil error.
Regression test: TestAbortedAuthError (fails before with "aborted error
for <nil> is nil").
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Two defects left the update directory in a mixed state after a failed upgrade was rolled back: - recoverFromFailedUpgrade only moves the purged old files back. Files that exist only in the new version and were already moved into the directory have no purged counterpart, so they stayed behind next to the old version. - copyAndCheckSHA256Sum (the copy fallback of moveFile) writes "<dst>.copy" and renames it into place. If the rename fails, the temporary file was never removed, and nothing cleans the main directory of .copy files. Fix: upgradeMoveFiles now returns the names of the new files it actually installed (index file and artifacts, also on failure). The rollback removes exactly those with os.Remove (never RemoveAll) unless the name had a purged old counterpart (restored over it) or is listed in Config.Ignore. Removal failures (e.g. files in use on Windows) are only logged, as for the existing restore step. copyAndCheckSHA256Sum now removes its temporary file when writing or renaming fails. Proof: TestRollbackRemovesNewOnlyFiles (missing last artifact) failed with 'unexpected leftover "aaa-new-only"'; TestRollbackLeavesNoCopyFiles (non-empty directory in the way) failed with 'unexpected leftover "portmaster.copy"'. Both pass now with -race. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
mergeStringList built a map to deduplicate and then sorted the keys. It runs for every domain, CNAME, ASN, country and IP that is in a filter list. The lists are a few names, so copy both into one slice, sort it and compact it. The result is unchanged: sorted, distinct, never nil, always a new slice. TestMergeStringListMatchesMap compares 50k random inputs (nil, empty, duplicates, within and across both slices) with the previous implementation. i7-14700HX, one CPU, -count=10, medians, per iteration of mergeStringList(nil, y) + mergeStringList(x, y) with n names each: n=0 58 ns 0 B 0 allocs -> 41 ns 0 B 0 allocs (-29%) n=1 347 ns 48 B 2 allocs -> 164 ns 48 B 2 allocs (-53%) n=3 1089 ns 112 B 2 allocs -> 461 ns 144 B 2 allocs (-58%) n=10 4120 ns 1232 B 8 allocs -> 1850 ns 480 B 2 allocs (-55%) The firewall DecideOnConnection benchmarks (also with lists) are unchanged within noise, as only a listed entity gets here, once per list key. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…er snapshot The wrapped config options of a layered profile (UseSPN, KeepHistory, EnableHistory, UseSplitTun, ...) read lp.RevisionCounter and lp.layers while holding only their own refresh lock. Update and increaseRevisionCounter write both under the write lock of the layered profile, and several callers use the options without any lock on the layered profile: checkTunneling (firewall/tunnel.go), the split tunnel check (firewall/split-tunnel.go), the history cleaner (netquery/database.go) and Connection.Save (network/connection.go). That is a data race on the revision counter and on the layers slice, which Update changes in place. Taking the read lock in the options is not an option: MatchFilterLists and other callers use them while the layered profile is locked for usage, and a second RLock deadlocks as soon as Update waits for the write lock in between. Publish an immutable snapshot of the revision counter and a copy of the layers in an atomic pointer instead. It is replaced whenever the revision counter changes, which always happens under the write lock, so callers that hold a lock see exactly what they saw before. The options only load the snapshot and take no lock on the layered profile. The config perspective of a layer is written once before the layer is shared. TestLayeredProfileOptionsWithoutLock produced 25 race reports before and none now. TestLayeredProfileOptionsDoNotLock shows that an option returns while a read lock is held and an update is waiting. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…e bandwidth map The eBPF bandwidth map holds absolute byte counters per 5-tuple, and the reporter passed them on as absolute values. Two things went wrong: - The counters outlive the connections of Portmaster. The entry of a UDP socket keeps counting after its connection ended, so the successor connection with the same 5-tuple started at zero and was credited with all bytes of its predecessors by its first update. - To skip unchanged entries, the reporter set Reported=1 by writing the whole entry back. That replaced rx and tx with the values read during the iteration and dropped whatever the kernel side had added in between (the UDP programs add to the entry atomically). Keep the reported counter values per map key in the reporter and send only what was added since as additive updates. The map is only read now. Unchanged entries are skipped by comparing with the remembered values, a counter that went backwards is treated as reset (as the consumer of absolute updates did), and the remembered values are only advanced once the update is queued, so a full queue delays bytes instead of dropping them. Remembered entries are dropped when they are gone from the map. As iterating a changing map may miss entries, every unseen entry is looked up first: forgetting a live entry would report all of its bytes again. The eBPF programs and generated objects are unchanged. The Reported field is simply not used anymore by the Go side. The reporter logic is covered by tests against a fake map source. The access to the real map (Iterate and Lookup) needs root and is not covered. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Process.GetExecHash had no callers (repo-wide grep, Go and UI) and three defects waiting for the first one: it wrote Process.ExecHashes without the process lock (the API export clones that map under the lock), it wrote to the map without ever allocating it (ExecHashes is never initialised anywhere, so the first call would panic with "assignment to entry in nil map"), and an unknown algorithm left the hasher nil and panicked in io.Copy. Remove the method instead of fixing code nobody runs. The ExecHashes field stays, as it is part of the exported process record. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…aits A TCP query hands itself to the connection handler through the buffered queries channel and only then starts waiting on its unbuffered Response channel. The handler delivered replies with a non-blocking send and treated a failed send as "the query gave up". When the query goroutine was not yet parked on its receive (e.g. preempted right after the buffered send, which is common under CPU load), the server's reply was silently dropped (or only cached) and the query timed out after defaultRequestTimeout (3s) although the server had answered. This hits any TCP/DoT query in production, most often when many queries are sent at once, e.g. after a reconnect. Give the Response channel room for the one reply, so delivering never blocks and never drops it. To keep caching replies that arrive after the query gave up, the query and the handler settle the query with a compare-and-swap: the handler delivers only if the query still waits, and a query that gives up uses a reply that was delivered meanwhile. Evidence: TestTCPResolverConcurrentReconnectDialsOnce failed with "query timed out", every failing run taking exactly 3.00s. Stress with 56 parallel processes of the race-built package test binary, each GOMAXPROCS=2 -test.run TestTCPResolver -test.count=20 -test.short: before 58 failures in 1120 runs, after 0 in 2240 runs. The new TestTCPResolverConnReplyBeforeQueryWaits fails deterministically with the previous delivery semantics and passes now. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…missing When reading the main directory failed with ErrNotExist, upgradeMoveFiles called utils.EnsureDirectory on the purge directory (which it had just created) although the error text says "create current directory". The main directory therefore stayed missing and moving the new index file into it failed, so the upgrade was rolled back. Impact: New() creates the main directory, so this only hits when the main directory disappears between startup and the upgrade (e.g. a user deletes the intel directory while Portmaster runs). Every following upgrade then failed until a restart, instead of re-creating the directory. Evidence: TestUpgradeCreatesMissingMainDirectory (New, remove main dir, upgrade) failed before with: upgrade failed, but recovery was successful: failed to move index file to .../installed/index.json: move failed, copy+delete fallback failed: write temp dst file: open .../installed/index.json.copy: no such file or directory It passes now with -race. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
moveFile falls back to copyAndCheckSHA256Sum when os.Rename fails (e.g.
EXDEV: on Linux the binary purge and download directories live in
/var/lib/portmaster while the main directory is /usr/lib/portmaster, which
can be different file systems). The log line says "copy+delete", but the
source was never deleted, so a "move" became a copy:
- upgradeMoveFiles: the old version's files were copied to the purge
directory but stayed in the main directory. Files the new version no
longer ships stayed there as stale, unindexed files (picked up by the
directory scan fallback in New and kept forever).
- recoverFromFailedUpgrade: restored files also stayed in the purge dir.
- downloads stayed in the download dir (harmless, cleanupAfterUpgrade
removes it).
Fix: after a successful (and, for artifacts, SHA256-verified) copy, remove
the source. A source that cannot be deleted (e.g. a file in use on
Windows) is only logged and left behind as before, so that this cannot
turn an upgrade that succeeded so far into one that always fails
(changed by the integrator on review). Directories are
unchanged: os.ReadFile on a directory fails, so the fallback still errors
out before deleting anything and the upgrade is rolled back (checked with
a probe test: main directory restored exactly, purge directory empty).
To test without a second file system, moveFile calls a package-level
renameFile (= os.Rename), which the tests replace.
Evidence: before the fix
TestUpgradeCopyFallbackRemovesSource:
unexpected file "zzz-old-only" in main directory after upgrade
unexpected file "aaa-new-only" left in download directory (and others)
TestRollbackWithCopyFallback:
unexpected file "assets.zip" left in purge directory after rollback
(and the other restored files)
Both pass now with -race.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Config.Ignore names entries in the main directory that the upgrade leaves in place (they are not moved to the purge directory). If the new version has an artifact (or index file) of the same name, moveFile overwrote the ignored file. It was never purged, so a rollback could not restore it, and recoverFromFailedUpgrade also skips ignored names when removing new files: after a failed upgrade the new content stayed in place and the original file was lost. Fix: an ignored regular file whose name the new version installs is moved to the purge directory like any other old file, so a rollback restores it. Ignored files that the new version does not replace, and ignored directories, are left alone as before. Why back up instead of skipping the artifact: the real configurations only ignore "uninstall.exe" in the Windows binary directory (Linux binaries and intel ignore nothing), and no release ships an artifact of that name, so their successful upgrades are unchanged either way. Skipping would leave the installed index listing an artifact whose file on disk does not match, which VerifyArtifacts reports as a corrupted installation (and for intel triggers a repair that could never succeed). Backing up keeps today's successful-upgrade result (the artifact is installed) and makes the rollback lossless. Directories are excluded because a purged directory cannot be renamed back over the installed file during rollback; for them the install still fails and is rolled back untouched (see TestRollbackLeavesNoCopyFiles). Evidence: TestRollbackRestoresIgnoredFileReplacedByArtifact (ignored "portmaster" with custom content, upgrade fails after installing it) failed before with: rollback_test.go:161: "portmaster" changed by rollback It passes now with -race. TestUpgradeIgnoredFiles pins the successful upgrade: the artifact replaces the ignored file, an unrelated ignored file stays unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Since the eBPF reporter sends additive deltas instead of absolute counters (b560240), an update for which no connection is found is lost for good: updateBandwidth dropped it, and unlike an absolute value the next update does not include those bytes. This happens when the kernel counts bytes of a flow slightly before Portmaster registered the connection, or between cleanup and re-creation of a connection. The Windows kext integrations (v1 and v2) also send additive updates and had the same loss. Additive updates without a connection are now held per connection ID in a small map owned by the single bandwidth update handler goroutine (no lock needed) and added to the next additive update of that ID that finds its connection. The merged update goes through applyBandwidthUpdate as before, so when the connection is locked, the held bytes are deferred on the connection together with the update and credited once. Absolute updates are unchanged. Bounds: - TTL 10s from the first held update of an entry: ten collect intervals of the 1s reporters, far more than the delay of registering a connection on its first packet, and short enough that bytes of a predecessor with the same 5-tuple are dropped instead of being credited to a successor (the bug fixed by b560240). Further updates do not extend the lifetime of an entry, so at most 10s worth of bytes is ever carried. - At most 4096 entries (well below 1 MiB). When full, expired entries are removed first, otherwise the new update is dropped as before rather than evicting valid entries. - Expired entries are swept at most once per second, driven by the passed-in time, so the map does not hold expired entries for flows Portmaster never tracks for longer than TTL plus 1s. Byte sums saturate instead of wrapping. Evidence: new tests in bandwidth_pending_test.go cover credited once within TTL, dropped after TTL, accumulation and saturation, the entry limit, absolute updates and the locked connection path. With the base behaviour (drop when not found) the credited, accumulation, limit and locked tests fail, e.g. "applied 5/1 bytes, want 105/11". The real reporter cannot be driven from service/firewall, as its types are unexported in its package, which cannot import service/firewall without an import cycle. The tests use connection IDs created like the reporters do instead. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
What: TestConnectOp (only run without -short) always failed with "failed to read request: EOF" after ~60ms, before any network access. The exit side of the connect op (ConnectOp.handleSetup) requires a terminal implementing terminal.SessionTerminal for rate limiting and otherwise stops the op with "no session available" (reported to the client as "[ext] internal error"). terminal.TestTerminal has no session, so the op was always stopped and the client side closed the app connection. The test now attaches a test terminal extension with a terminal.SessionAddOn to the exit side terminal. The test still needs -short to be skipped: the connect op only dials IPs in the global scope (netutils.GetIPScope check in ConnectOp.setup, independent of the exit policy), so a loopback/LAN listener is always denied and the test cannot be made hermetic without a production change. The skip message and a comment now say so. Impact: test-only. No production code changed. This was not a bug in the connect op: the real exit side always runs on a CraneTerminal, which has a session. Evidence: before: FAIL (EOF, connection marked failed with "the exit node reported an error: [ext] internal error"). After: PASS (HTTP 301 from orf.at), go test -race -count=50 -run TestConnectOp ./spn/crew/: 50/50 PASS. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
perf(database/sqlite): write records without a RETURNING clause
The smoke test now waits until the filter lists are downloaded and loaded, then checks that a tracker on the default lists is blocked and that the block names the lists. This covers the intel updater, the list decoder and the SQLite cache database, which the other checks do not. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
test(vmtest): check filter list blocking in the Linux smoke test
The process module looked up the path of the UI binary once at start and logged an error if it was missing. Installations without the UI (servers, headless setups) showed this error in every debug info, and when the updater installed the UI after start, the UI was not recognized as such until a restart. The path is now looked up when it is needed, again every 10 seconds while the UI is missing, and compared by its real path. A missing UI is logged at info level. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With the UI path no longer logged as an error, a normal run logs no errors, so any ERR or CRT line now points to a problem and fails the test, with the first lines shown. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
fix(process): look up the UI path lazily and do not log it as an error
…mmand `portmaster-core update` installed the new binaries and then failed with "binary update failed: action required: restart required" and exit code 1, and the updater logged the same as a worker error. Scripts calling the command saw a failure after a successful update. The restart-required result now has its own error, ErrRestartRequired, which ForceUpdate (used only by tools) logs at info level and treats as success. The service still notifies the user to restart. The Windows smoke test now checks the exit code of the update command. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
fix(updates): report an installed upgrade as success in the update command
Upstream safing#1981 reports blocked connections that only fail after a 25-30 second timeout. The smoke tests now time a connection blocked by a rule and fail if it takes 5 seconds or more. Windows: 0.1 s, Linux: 1.0 s, both with curl exit code 7 (connection refused). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
test(vmtest): check that blocked connections fail at once
…ws code in CI Semver-compatible updates: anyhow 1.0.104 (unsound downcast_mut), webpki-roots 0.26.11 / 1.0.12 (distrusted emSign intermediates), plist 1.10 and notify-rust 4.17 (quick-xml >= 0.41). The direct tauri-winrt-notification dependency goes from 0.3 to 0.8, the last user of quick-xml 0.31; its activation callback now returns the Result type of the windows crate it is built with, so the closure leaves it to inference. cargo audit: 13 -> 8 vulnerabilities; the rest are in optional dependencies that are not compiled (rustls 0.22 of tokio-websockets, rkyv of rust_decimal). The Windows-only code of the UI was only compiled for releases. A new CI job runs clippy for x86_64-pc-windows-gnu, the target of the installer. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The new Windows clippy job found them. One is a bug: starting the service when it is not installed ran sc.exe anyway, because open_service() reports a missing service as Ok(false), not as an error. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The status came from `systemctl is-active`. That prints "inactive"
for units that do not exist, so a missing service was shown as stopped
with a "Start Now" button, and the "please reinstall" message was never
shown. A failed service ("failed") was not handled and ended in an
error instead of the start button.
`systemctl show -p LoadState -p ActiveState` answers both in one call
and exits with 0 for missing units: LoadState=not-found is not
installed, ActiveState active/reloading/refreshing is running, any other
state is stopped.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
fix(tauri): update dependencies with security advisories, check Windows code in CI
Most systems have systemctl in only one of the four checked paths, so every UI start logged errors for the others. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
fix(tauri): report a missing or failed system service correctly on Linux
Until the first intel download (first start, offline), the core logged three warnings per connection: filter lists not loaded, no geoip update and no location data. A 30 minute soak test without intel data had about 3,500 of them and no other warning. The filter list module already sets a state the UI shows, and the update module reports the missing data. These cases are now debug messages; other geoip errors stay warnings. geoip.ErrDatabaseNotAvailable is exported to tell them apart. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
fix(intel): do not warn on every connection while intel data is missing
…ew socket DNS lookups through Portmaster failed now and then with a 3 second timeout (about 3% of uncached lookups in the Linux VM, 0% without Portmaster). The upstream query of the Portmaster resolver was sent back to the Portmaster nameserver itself: 1. systemd-resolved queries 10.0.2.3:53 from some port. Portmaster redirects it to its nameserver and keeps the connection, with the verdict "reroute to nameserver", for 10 minutes after it ended. 2. The OS gives the same port to a new socket of the Portmaster resolver for a query to the same server. Its packets have the same address tuple, so they matched the old connection and got its verdict without being looked at, and its conntrack entry still held the DNAT. Ended connections now no longer take packets: the packet dispatcher removes such a connection from the state (it stays in the history) and handles the packet as a new connection, which also fixes the process attribution for any program that reuses a tuple. Before the Portmaster resolver sends the first packet of a new UDP socket, it also ends a connection with that tuple that is not marked as ended yet (the old socket is gone, as the OS handed out its port) and deletes its conntrack entry on Linux. The plain resolver now also resends a UDP query after 1 second without reply, within the same timeout, as stub resolvers do (RFC 1035 4.2.1). That was not the cause here, but a single lost packet failed the query before. Linux VM, 600 uncached lookups in bursts of 10: 21-29 slower than 2 s and as many resolver timeouts before, 0 and 0 after. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Until the filter list index is downloaded (first start, offline), the global profile cannot resolve the filter list IDs. It then showed the warning "Internal Settings Failure" in the UI and retried every 15 seconds, each retry logged as a failed worker (ERR), until the lists were there: on a fresh VM 35 seconds, which made the Linux smoke test fail now and then. A missing index is now retried quietly. Only one retry is pending at a time; before, every config change during a failure added another retry chain. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
fix(profile): do not report missing intel data as a settings failure
apt hung for over 30 minutes on a PR run. The step now gives up after 10 minutes and apt retries and times out requests itself. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
fix(firewall): do not apply the verdict of an ended connection to a new socket
ci: time out the MinGW install step of the Windows clippy job
On the first start the filter list index is not downloaded yet. App profiles with their own filter lists then logged a warning and fell back to the global filter lists until the profile was reloaded for another reason, e.g. a settings change or a core restart. Profiles now remember that their filter lists are pending. Once the global config profile resolves its filter lists, which it retries until the index is there, all active profiles with pending lists are marked as outdated and reloaded on their next use. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Opened here by mistake, this belongs to a fork. Sorry for the noise. |
|
|
|
Important Review skippedToo many files! This PR contains 652 files, which is 352 over the limit of 300. To get a review, reduce the PR to 300 files or fewer by splitting it into smaller PRs or changing its base branch. Usage-priced reviews support at most 500 files.
|
Problem
On the first start the filter list index is not downloaded yet. App profiles with their own filter lists logged
profiles: failed to resolve filter list IDs: file not foundand silently used the global filter lists until the profile was reloaded for some other reason (settings change, core restart).Fix
Profile.parseConfig:updates.ErrNotFoundfromResolveListIDsmarks the profile's filter lists as pending (debug log instead of a warning). Other errors still warn.updateGlobalConfigProfilealready retries every 15 s until the index is there (Update to latest portbase updater changes and register index files #48). When its filter lists resolve, all active profiles with pending lists are marked outdated, soLayeredProfile.Updatereloads them on their next use.Tests
TestReloadProfilesWithPendingFilterLists.go test ./service/profile/, golangci-lint (new-from-rev): clean.🤖 Generated with Claude Code